package com.example.RTKSDK;

import android.Manifest;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Handler;
import android.os.Looper;

import androidx.core.app.ActivityCompat;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.UUID;

/**
 * RTK设备蓝牙连接以及NMEA数据解析SDK
 */
public class BluetoothNMEASDK {
    // 蓝牙标准串口服务UUID
    private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

    private final Context context;
    private BluetoothAdapter bluetoothAdapter;
    private BluetoothSocket bluetoothSocket;
    private volatile boolean isReading = false;
    private Thread dataThread;
    private final Handler mainHandler = new Handler(Looper.getMainLooper());

    // 回调接口
    public interface SDKCallback {
        // 请求蓝牙权限
        void onPermissionRequired(String[] permissions);
        // 找到蓝牙设备(已连接的)
        void onDeviceFound(BluetoothDevice device);
        // 蓝牙设备扫描完成
        void onDiscoveryFinished();
        // 设备连接
        void onConnected();
        // 设备断开
        void onDisconnected();
        // 接收到数据
        void onDataReceived(LocationData data);
        // 发生错误
        void onError(String message);
    }

    private SDKCallback callback;

    public BluetoothNMEASDK(Context context, SDKCallback callback) {
        this.context = context.getApplicationContext();
        this.callback = callback;
        this.bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    }

    // 1. 检查并请求权限
    public boolean checkPermissions() {
        List<String> requiredPermissions = new ArrayList<>();
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH) != PackageManager.PERMISSION_GRANTED) {
            requiredPermissions.add(Manifest.permission.BLUETOOTH);
        }
        // Android 12+ 权限
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S) {
            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
                requiredPermissions.add(Manifest.permission.BLUETOOTH_CONNECT);
            }
            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH_SCAN) != PackageManager.PERMISSION_GRANTED) {
                requiredPermissions.add(Manifest.permission.BLUETOOTH_SCAN);
            }
        } else {
            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                requiredPermissions.add(Manifest.permission.ACCESS_FINE_LOCATION);
            }
        }

        if (!requiredPermissions.isEmpty()) {
            callback.onPermissionRequired(requiredPermissions.toArray(new String[0]));
            return false;
        }
        return true;
    }

    // 2. 扫描蓝牙设备
    @SuppressLint("MissingPermission")
    public void startDiscovery() {
        if (!checkPermissions()) return;

        if (bluetoothAdapter == null) {
            callback.onError("设备不支持蓝牙");
            return;
        }

        if (bluetoothAdapter.isDiscovering()) {
            bluetoothAdapter.cancelDiscovery();
        }

        // 获取已配对设备
        Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
        for (BluetoothDevice device : pairedDevices) {
            callback.onDeviceFound(device);
        }

        // 注册广播接收器来发现新设备
        IntentFilter filter = new IntentFilter();
        filter.addAction(BluetoothDevice.ACTION_FOUND);
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        context.registerReceiver(discoveryReceiver, filter);

        // 开始扫描附近设备
        if (!bluetoothAdapter.startDiscovery()) {
            callback.onError("无法开始扫描");
        }
    }

    // 新增广播接收器
    private final BroadcastReceiver discoveryReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                // 发现新设备
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                if (device != null) {
                    callback.onDeviceFound(device);
                }
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                // 扫描完成
                context.unregisterReceiver(discoveryReceiver);
                callback.onDiscoveryFinished();
            }
        }
    };


    // 3. 连接设备
    @SuppressLint("MissingPermission")
    public void connectToDevice(BluetoothDevice device) {
        new Thread(() -> {
            try {
                // 连接设备之前已经校验过权限，且此权限只在android 12+有效
//                if (ActivityCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
//                    return;
//                }
                bluetoothSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
                bluetoothSocket.connect();
                mainHandler.post(() -> callback.onConnected());
                startListening();
            } catch (IOException e) {
                mainHandler.post(() -> callback.onError("连接失败: " + e.getMessage()));
                disconnect();
            }
        }).start();
    }

    // 4. 监听数据
    private void startListening() {
        isReading = true;
        dataThread = new Thread(() -> {
            try (InputStream inputStream = bluetoothSocket.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
                String nmeaSentence;
                NMEAParser parser = new NMEAParser();

                while (isReading && (nmeaSentence = reader.readLine()) != null) {
                    // 处理GGA数据
                    if (nmeaSentence.contains("GGA")) {
                        LocationData data = parser.parse(nmeaSentence);
                        if (data != null) {
                            mainHandler.post(() -> callback.onDataReceived(data));
                        }
                    }
                }
            } catch (IOException e) {
                if (isReading) {
                    mainHandler.post(() -> callback.onError("数据读取错误: " + e.getMessage()));
                }
            }
        });
        dataThread.start();
    }

    // 5. 停止连接
    public void disconnect() {
        isReading = false;
        if (dataThread != null) {
            dataThread.interrupt();
            dataThread = null;
        }
        try {
            if (bluetoothSocket != null) {
                bluetoothSocket.close();
            }
        } catch (IOException e) {
            callback.onError("断开连接错误: " + e.getMessage());
        }
        mainHandler.post(() -> callback.onDisconnected());
    }
}